package com.g3d.objects;

import com.g3d.core.G3DSoundManager;

public class G3DSound 
{

	private final G3DSoundManager _manager;

	private float _leftVolume = 1.0f;
	private float _rightVolume = 1.0f;
	
	private int _soundId;
	private int _streamId;

	private int _loopsCount;
	private float _rate;
	
	public G3DSound(int soundId, G3DSoundManager manager)
	{
		this._manager = manager;
		this._soundId = soundId;
	}

	public int getSoundId()
	{
		return this._soundId;
	}
	
	public float getLeftVolume()
	{
		return this._leftVolume;
	}
	
	public float getRightVolume()
	{
		return this._rightVolume;
	}

	public void setLoopsCount(int loops)
	{
		this._loopsCount = loops;
		if(this._streamId != 0) 
		{
			this._manager.getSoundPool().setLoop(this._streamId, this._loopsCount);
		}
	}

	public void setRate(float rate)
	{
		this._rate = rate;
		if(this._streamId != 0) 
		{
			this._manager.getSoundPool().setRate(this._streamId, this._rate);
		}
	}
	
	public void play()
	{
		float actualLeft = this._leftVolume * this._manager.masterVolume();
		float actualRight = this._rightVolume * this._manager.masterVolume();
		this._streamId = this._manager.getSoundPool().play(this._soundId, actualLeft, actualRight, 1, this._loopsCount, this._rate);
	}

	public void stop()
	{
		if(this._streamId != 0)
		{
			this._manager.getSoundPool().stop(this._streamId);
		}
	}

	public void pause()
	{
		if(this._streamId != 0)
		{
			this._manager.getSoundPool().pause(this._streamId);
		}
	}

	public void resume()
	{
		if(this._streamId != 0)
		{
			this._manager.getSoundPool().resume(this._streamId);
		}
	}
	
	public void setLooping(boolean loop)
	{
		this.setLoopsCount((loop) ? -1 : 0);
	}

	public void setVolume(float leftVolume, float rightVolume)
	{
		this._leftVolume = leftVolume;
		this._rightVolume = rightVolume;
		if(this._streamId != 0)
		{
			float actualLeft = this._leftVolume * this._manager.masterVolume(); 
			float actualRight = this._rightVolume * this._manager.masterVolume();
			
			this._manager.getSoundPool().setVolume(this._streamId, actualLeft, actualRight);
		}
	}
	public void updateVolume()
	{
		if(this._streamId != 0)
		{
			float actualLeft = this._leftVolume * this._manager.masterVolume(); 
			float actualRight = this._rightVolume * this._manager.masterVolume();
			
			this._manager.getSoundPool().setVolume(this._streamId, actualLeft, actualRight);
		}
	}
	
}
